import { routes } from "@/constants/routes";
import { getGlobalData, setGlobalData } from "@/global_data";
import { redirectToWithParams, switchTab } from "@/helper/utils";
import { getAd, wxLogin } from "@/services/entities/all";
import { View, Video, Image } from "@tarojs/components";
import Taro, { useDidHide, useRouter } from "@tarojs/taro";
import { useEffect, useRef, useState } from "react";
import "./index.scss";

const InitPage = () => {
  const router = useRouter();
  const { route, action, ...otherParams } = router.params;
  const timer = useRef<any>();
  const isShowAd = getGlobalData("isShowAd");
  const [ad, setAd] = useState<any>({});
  const loginSuccess = () => {
    setGlobalData("isShowAd", true);
    if (route && routes[route.toUpperCase()]) {
      if (action === "redirect") {
        redirectToWithParams(routes[route.toUpperCase()], otherParams);
      }
      if (action === "switch") {
        switchTab(routes[route.toUpperCase()]);
      }
    } else {
      switchTab(routes.ROUTES_INDEX);
    }
  };

  const init = async () => {
    const adData: any = await getAd();
    console.log("adData", adData);
    const hasData = adData && (adData.imageUrl || adData.videoUrl);
    if (hasData) {
      setAd(adData);
    }
    Taro.login().then((res) => {
      wxLogin({ code: res.code }).then((response: any) => {
        console.log("sss", response);
        setGlobalData("userInfo", response);
        if (route !== "ROUTES_SHOP_DETAIL" && !isShowAd && hasData) {
          timer.current = setTimeout(() => {
            loginSuccess();
          }, 3500);
        } else {
          loginSuccess();
        }
      });
    });
  };
  const toDetail = () => {
    if (ad.storeId) {
      setGlobalData("isShowAd", true);
      clearTimeout(timer.current);
      redirectToWithParams(routes.ROUTES_SHOP_DETAIL, { storeId: ad.storeId });
    }
  };

  useDidHide(() => {
    clearTimeout(timer.current);
  });

  const getInitBanner = () => {
    if (ad.videoUrl) {
      return (
        <Video
          className="video"
          autoplay={true}
          controls={false}
          src={ad.videoUrl}
          onClick={toDetail}
        ></Video>
      );
    }
    if (ad.imageUrl) {
      return <Image src={ad.imageUrl} className="video" onClick={toDetail} />;
    }
    return null;
  };

  useEffect(() => {
    init();
  }, []);
  return (
    <View className="flex-center bg-page">
      {!isShowAd ? getInitBanner() : ""}
    </View>
  );
};

export default InitPage;
